<!-- 可控多选标签输入框（仅支持多选） -->
<template>
    <div class="relative width-all" style="height: 32px;">
        <el-input ref="dataSelectInput" clearable readonly class="input_style"
            @click="selectUnit">
            <template #append><i class="icon-base icon-base-contactbookV2"></i></template>
        </el-input>
       <div class="simulation_box" @click="selectUnit">
            <el-space :size="[5,5]" class="margin-top-l" v-if="amoebaMode">
                <el-tag closable effect="light" v-for="(aItem, aIndex) in selectedAmoebaItems" size="small" :key="aItem.id"
                    @close="tagClose(aItem, aIndex)">
                    {{ aItem.amoebaName }}
                </el-tag>
            </el-space>
            <el-space :size="[5,5]" class="margin-top-l" v-else>
                <el-tag closable effect="light" v-for="(rItem, rIndex) in selectedItems" size="small" :key="rItem.value" 
                    @close="tagClose(rItem, rIndex)">
                    {{ rItem.label }}
                </el-tag>
            </el-space>
            <p v-if="selectedItems.length <= 0 && selectedAmoebaItems.length <= 0" class="text-gray font-sm">
                {{ props.placeholder || '请选择' }}
            </p>
        </div>
        
        <!-- 单位选择 弹框 -->
        <el-dialog v-model="unitDialogShow" title="选择员工" :width="680" 
            draggable align-center append-to-body :close-on-click-modal="false" :before-close="unitDialogClose">
            <div class="transfer_container">
                <div class="transfer_left_container">
                    <div class="transfer_oper_container">
                        <el-input v-model="searchValue" clearable placeholder="请输入关键字" :suffix-icon="Search"
                            @input="searchInput" />
                    </div>
                    <el-tabs v-model="active" class="demo-tabs" @tab-click="tabsChange">
                        <el-tab-pane label="按人员选择" :name="0">
                            <div class="user_list" v-if="active == 0" v-loading="loading">
                                <el-row :gutter="24" class="width-all">
                                    <el-col :span="24" class="user_item">
                                        <el-checkbox v-model="checkAll" label="全集团"
                                            @change="(checkState) => { changeItem( 'all', checkState ) }" />
                                    </el-col>
                                    <el-col :span="24" v-for="item in filtersOptions" :key="item.value" class="user_item">
                                        <el-checkbox v-model="item.checked" :label="item.label" :disabled="item.disabled"
                                            @change="(checkState) => { changeItem( item, checkState ) }" />
                                    </el-col>
                                </el-row>
                            </div>
                        </el-tab-pane>
                        <el-tab-pane label="按巴体选择" :name="1">
                            <div class="tree_list" v-if="active == 1" v-loading="loading">
                                <el-tree ref="treeRef" :data="amoebaOptions" :default-expand-all="true" 
                                    :check-strictly="false" show-checkbox :check-on-click-node="true" 
                                    :props="treeProps" node-key="id" @check="amoebaCheckChange" />
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                </div>
                <div class="transfer_right_container">
                    <div class="transfer_oper_container">
                        <div class="flex space-between">
                            <p v-if="checkAll">已选：<span>{{ checkedAllCount }}个员工</span></p>
                            <p v-else>已选：<span>{{ checkedTotal }}个员工</span></p>
                            <el-text type="primary" class="cursorPointer" @click="bulkChecked(false)">清 空</el-text>
                        </div>
                    </div>
                    <div class="checked_tag_container">
                        <ul v-if="active == 0">
                            <li v-if="checkAll">
                                <el-tag size="large">全集团</el-tag>
                            </li>
                            <li v-for="item in dataOptions" :key="item.value" class="checked_item">
                                <div v-if="item.checked" class="margin-bottom-sm flex space-between" style="padding: 3px 5px;">
                                    <el-tag size="large">{{ item.label }}</el-tag>
                                    <i class="icon-base icon-base-delete-filling close_icon" @click="unCheckedItem(item)"></i>
                                </div>
                            </li>
                        </ul>
                        <ul v-if="active == 1">
                            <li v-for="item in amoebaList" :key="item.id">
                                <div v-if="item.checked" style="padding: 3px 5px;">
                                    <el-tag size="large">{{ item.amoebaName }}</el-tag>
                                </div>
                            </li>
                        </ul>
                        <el-empty :image-size="80" v-if="(checkedAllCount <= 0 && checkedTotal <= 0) && amoebaCheckedTotal <= 0" />
                    </div>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="unitDialogClose"> 取 消 </el-button>
                    <el-button type="primary" @click="confirm"> 确 定 </el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
    // 通讯录 PC人员索引列表 
    import { ref, watch, computed, onMounted, nextTick } from "vue"
    import { Search } from '@element-plus/icons-vue'
    import { listUserV2 } from "@/api/system/user";
    import { listAmoeba, getUserListByAmoebaId } from "@/api/system/amoeba";
    import useUserStore from '@/store/modules/user'
    const props = defineProps( [ 'modelValue', 'single', 'filterIds', 'filterSelf', 'readonly', 'placeholder' ] );
    const emit = defineEmits( [ 'update:modelValue', 'confirm', 'change' ] );
    const { proxy } = getCurrentInstance();
    const treeRef = ref(null);
    const searchValue = ref(''); // 搜索关键字
    const dataOptions = ref([]);
    const selectedItems = ref([]);
    const selectedAmoebaItems = ref([]);
    const filterValues = ref(props.filterIds || []); // 备用值
    const active = ref(0); // tabs选中项
    const loading = ref(false);
    const unitDialogShow = ref(false); // 单位选择弹框显隐

    const checkAll = ref(false); // 是否开启全集团模式
    const checkedAllCount = ref(0); // 全集团人数统计
    const amoebaMode = ref(false); // 巴体模式
    const amoebaList = ref([]);
    const amoebaOptions = ref([]);
    const treeProps = ref({ label: 'amoebaName' });
    // 列表过滤计算属性 两层过滤 1：搜索过滤 2：传入过滤项过滤
    const filtersOptions = computed( () => dataOptions.value.filter( item => 
        item.label.includes(searchValue.value) && filterValues.value.findIndex( cItem => cItem == item.value ) < 0
    ));
    // 已选择数量统计计算属性
    const checkedTotal = computed( () => dataOptions.value.filter( item => item.checked == true ).length )
    const amoebaCheckedTotal = computed( () => amoebaList.value.filter( item => item.checked == true ).length )
    // 弹框显隐状态监听
    watch(() => unitDialogShow.value, () => {
        if(unitDialogShow.value){
            console.log('当前模式：', amoebaMode.value ? '巴体模式' : '用户模式');
            if(amoebaMode.value){
                active.value = 1;
                nextTick( () => {
                    const amoebaIds = selectedAmoebaItems.value.map( item => item.id );
                    treeRef.value.setCheckedKeys(amoebaIds || [], false)
                });
                return
            }
            if(props.modelValue && props.modelValue.length){
                setDefaultCheckedItems();
            }
        }
    }, { deep: true });
    // 双向绑定值监听
    watch(() => props.modelValue, () => {
        nextTick(() => {
            if(!props.modelValue || props.modelValue.length <= 0) {
                amoebaMode.value = false;
                selectedAmoebaItems.value = [];
                checkAll.value = false;
                amoebaList.value.map( item => item.checked = false);
            };
            setDefaultCheckedItems();
        });
    }, { deep: true, immediate: true });
    // 集团选择状态监听
    watch(() => checkAll.value, () => {
        // 其他人员选择的可选状态受集团选择限制
        dataOptions.value.map( item => { item.disabled = checkAll.value; item.checked = false; })
        checkedAllCount.value = checkAll.value ? dataOptions.value.length : 0
    }, { deep: true, immediate: true });
    watch(() => props.filterIds, () => {
        const filterTimeIds = props.filterIds || []
        filterValues.value = JSON.parse(JSON.stringify(filterTimeIds));
        const isCheckAll = filterValues.value.findIndex( item => item == '0') >= 0
        if(isCheckAll){
            if(dataOptions.value.length > 0){
                filterValues.value = dataOptions.value.map( item => item.value );
            }else{
                nextTick(()=>{ getUserList(true) })
            }
            return
        }
        if(props.filterSelf){
            const selfUserId = useUserStore().id;
            filterValues.value.push(selfUserId)
        }
    }, { deep: true, immediate: true });

    // 左侧选择 保留方法
    const changeItem = (checkItem, checkState) => {};
    // 右侧取消选择
    const unCheckedItem = (checkedItem) => {
        checkedItem.checked = false;
    };
    // 标签移除
    const tagClose = (item, index) => {
        if(item.value == '0' && item.label == '全集团'){
            checkAll.value = false;
            updateData();
            return
        }
        if(amoebaMode.value){
            item.checked = false
            updateAmoebaData();
            return
        }
        const itemValue = item.value;
        dataOptions.value.map( fItem => {
            if( fItem.value == itemValue ) item.checked = false;
        });
        updateData();
    };
    // 搜索 保留方法
    const searchInput = (value) => {};
    // 选择项清空
    const bulkChecked = (state) => {
        checkAll.value = false; // 不管是否全集团模式，都变为直接关闭
        dataOptions.value.map( item => { item.checked = state; });
        if(amoebaMode.value){
            amoebaList.value.map( item => item.checked = false );
            treeRef.value.setCheckedKeys([], false)
        }
    }
    // tabs切换
    const tabsChange = (e) => {
        active.value = e.paneName;
        active.value == 1 ? getAmoebaList() : getUserList()
        searchValue.value = '';
    };
    // 选择弹框启动
    const selectUnit = () => {
        if(props.readonly) return // 只读模式无法启动弹框
        unitDialogShow.value = true;
    };
    // 驱动默认值更新
    const setDefaultCheckedItems = () => {
        const defalutValues = props.modelValue || [];
        if(!dataOptions.value || dataOptions.value.length <= 0) return
        
        const isCheckedAll = defalutValues.findIndex( item => item == '0' )
        if( isCheckedAll >= 0 ) {
            console.log('默认进入全集团模式');
            checkAll.value = true;
            selectedItems.value = [{ label: '全集团', value: '0', checked: true }];
            dataOptions.value.map( item => { item.disabled = true; item.checked = false; })
            return
        }
        if(amoebaMode.value){
            nextTick( () => {
                const amoebaIds = selectedAmoebaItems.value.map( item => item.id );
                treeRef.value && treeRef.value.setCheckedKeys(amoebaIds || [], false)
                amoebaList.value.map( item => {
                    amoebaIds.map( cItem => {
                        if(item.id == cItem) item.checked = true;
                    })
                });
            });
            return
        }
        if(defalutValues.length){
            dataOptions.value.map( item => {
                defalutValues.map( id => {
                    if( id != item.value ) return
                    item.checked = true;
                })
            });
        }else{
            dataOptions.value.map( item => item.checked = false );
        }
        selectedItems.value = dataOptions.value.filter( item => item.checked );
    };
    // 驱动内容更新
    const updateData = () => {
        let checkedItems = [];
        if(checkAll.value){ // 全集团模式
            console.log('进入全集团模式');
            checkedItems = [{ label: '全集团', value: '0', checked: true }];
        }else{ // 局部选择模式
            console.log('进入局部选择模式');
            checkedItems = dataOptions.value.filter( item => item.checked )
        }
        selectedItems.value = checkedItems;
        const checkedValues = checkedItems.map( item => item.value );
        emit('update:modelValue', checkedValues);
        emit('change', checkedItems);
    };
    const updateAmoebaData = () => {
        const checkedItems = amoebaList.value.filter( item => item.checked );
        selectedAmoebaItems.value = checkedItems;
        const checkedAmoebaValues = checkedItems.map( item => item.id );
        let checkedValues = [];
        checkedAmoebaValues.map( async (item) =>  {
            const res = await getUserListByAmoebaId({ amoebaId: item });
            const values = res.data || [];
            const valuesUserIds = values.map( aItem => aItem.userId );
            checkedValues = [ ...checkedValues, ...valuesUserIds ];
            if(checkedValues.length <= 0) return
            emit('update:modelValue', checkedValues);
        });
        emit('change', checkedItems);
    };
    // 提交保存
    const confirm = () => {
        amoebaMode.value  = active.value ? true : false
        amoebaMode.value ? updateAmoebaData() : updateData();
        unitDialogShow.value = false;
        checkAll.value = false;
        active.value = 0;
    };
    // 弹框关闭
    const unitDialogClose = () => {
        unitDialogShow.value = false;
        checkAll.value = false;
        active.value = 0;
    };
    const amoebaCheckChange = (a, b, c) => {
        a.checked = a.checked ? false : true;
    };
    const getUserList = (checkState) => {
        loading.value = true;
        listUserV2().then(res => {
            loading.value = false;
            dataOptions.value = [];
            const userList = res.data || [];
            userList.map( item => {
                const obj = { label: item.nickName || '神秘人', value: item.userId }
                dataOptions.value.push(obj);
            });
            if(checkState) {
                filterValues.value = dataOptions.value.map( item => item.value );
            }
            setDefaultCheckedItems();
        });
    };
    const getAmoebaList = () => {
        loading.value = true;
        listAmoeba().then(response => {
            loading.value = false;
            const amoebaTimeList = response.data || [];
            amoebaList.value = amoebaTimeList.filter( item => filterValues.value.findIndex( cItem => cItem == item.id ) < 0 );
            amoebaOptions.value = proxy.handleTree(amoebaList.value || [], "id");
            setDefaultCheckedItems();
        });
    };
    onMounted(() => { getUserList(); });
</script>
<style lang="scss" scoped>
    :deep(.el-tree-node .is-leaf + .el-checkbox .el-checkbox__inner) {
        display: inline-block;
    }
    :deep(.el-tree-node .el-checkbox .el-checkbox__inner) {
        display: none;
    }

    :deep(.el-input-group__append){
        padding: 0 10px;
    }
    :deep(.el-tabs__header){
        margin: 0;
    }
    :deep(.el-tabs__nav){
        width: 100%;
    }
    :deep(.el-tabs__item){
        width: 50%;
    }
    :deep(.el-row){
        margin: 0!important;
    }
    .transfer_container{
        border: 1px solid #dcdcdc;
        height: 452px;
        border-radius: 5px;
        display: flex;
        .transfer_right_container{
            width: 50%;
            height: 100%;
            border-left: 1px solid #dcdcdc;
        }
        .transfer_left_container{
            width: 50%;
            height: 100%;
        }
        .transfer_oper_container{
            height: 50px;
            line-height: 50px;
            width: 100%;
            padding: 0 10px;
            box-sizing: border-box;
            border-bottom: 1px solid #dcdcdc;
        }
        .user_list{
            height: 360px;
            overflow-y: auto;
            padding: 8px 12px;
            box-sizing: border-box;
            .user_item{
                cursor: pointer;
                border-radius: 5px;
                transition: 300px;
                background-color: #fff;
            }
            .user_item:hover{
                background-color: #eee;
            }
        }
        .checked_tag_container{
            padding: 8px 12px;
            height: 400px;
            overflow-y: auto;
            .close_icon{
                display: none;
                font-size: 22px;
                margin-top: 5px;
                color: #999;
                cursor: pointer;
            }
            .checked_item{
                background-color: #fff;
                border-radius: 5px;
            }
            .checked_item:hover{
                background-color: #eee;
                .close_icon{
                    display: inline-block;
                }
            }
        }
        .tree_list{
            padding: 12px 10px;
        }
    }
    .simulation_box{
        position: absolute;
        left: 2px;top: 1px;
        z-index: 99;
        max-width: calc( 100% - 42px );
        overflow-x: auto;
        overflow-y: hidden;
        border-radius: 5px;
        min-height: 28px;
        line-height: 30px;
        padding: 0 8px;
        cursor: pointer;
    }
</style>